package com.zmn.oms.services.impl.product;

import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.persistence.interfaces.product.OrderProductExtendDao;
import com.zmn.oms.services.interfaces.product.OrderProductExtendService;
import io.shardingsphere.api.HintManager;
import io.shardingsphere.core.keygen.DefaultKeyGenerator;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 类描述：工单产品扩展实现
 * @author heciqi
 * @date 2018/12/05 17:13
 */
@Service
public class OrderProductExtendServiceImpl implements OrderProductExtendService {

	@Resource
	protected OrderProductExtendDao orderProductExtendDao;

	@Autowired
	protected DefaultKeyGenerator defaultKeyGenerator;

	/**
	 * 按订单id查询扩展数量
	 * @param orderId
	 * @return
	 */
	@Override
	public int countByOrderId(Long orderId) {
		return orderProductExtendDao.countByOrderId(orderId);
	}

	/**
	 * 主键查询
	 *
	 * @param proExtId
	 * @return
	 */
	@Override
	public OrderProductExtend findOrderProductExtendByKeySrcMaster(Long orderId,Long proExtId) {
		try (HintManager hintManager = HintManager.getInstance()) {
			hintManager.setMasterRouteOnly();
			return orderProductExtendDao.findOrderProductExtendByKey(orderId,proExtId);
		}
	}

	/**
	 * 工单查询产品扩展
	 *
	 * @param orderId
	 * @return
	 */
	@Override
	public List<OrderProductExtend> listByOrderIdSrcMaster(Long orderId) {
		try (HintManager hintManager = HintManager.getInstance()) {
			hintManager.setMasterRouteOnly();
			return orderProductExtendDao.listByOrderId(orderId);
		}
	}

	/**
	 * 工单查询产品扩展
	 *
	 * @param orderId
	 * @return
	 */
	@Override
	public List<OrderProductExtend> listByOrderId(Long orderId) {
		return orderProductExtendDao.listByOrderId(orderId);
	}

	/**
	 * 批量插入
	 *
	 * @param orderProductExtends
	 * @return
	 */
	@Override
	public Integer insertAll(List<OrderProductExtend> orderProductExtends) {
		if (CollectionUtils.isEmpty(orderProductExtends)) {
			return 0;
		}

		orderProductExtends.forEach(orderProductExtend -> {
			orderProductExtend.setProExtId(defaultKeyGenerator.generateKey().longValue());
		});
		return orderProductExtendDao.insertAll(orderProductExtends);
	}

	/**
	 * 按订单删除
	 *
	 * @param orderId
	 * @return
	 */
	@Override
	public Integer deleteByOrderId(Long orderId) {
		return orderProductExtendDao.deleteByOrderId(orderId);
	}

	/**
	 * 通过订单ID和旧的产品ID改产品ID和产品名称
	 * @param orderProductExtend
	 * @return
	 */
	public int updateByOrderIdAndOldProductId(OrderProductExtend orderProductExtend) {
		if (orderProductExtend == null
				|| orderProductExtend.getOrderId() == null || orderProductExtend.getOldProductId() == null
				|| orderProductExtend.getProductId() == null || orderProductExtend.getProductName() == null) {
			return 0;
		}
		return orderProductExtendDao.updateByOrderIdAndOldProductId(orderProductExtend);
	}
}
